package com.nb.protocol.service;

import com.nb.protocol.protocol.MessageHolder;
import com.nb.protocol.queue.TaskQueue;
import com.nb.protocol.util.ThreadPoolBuilder;
import org.apache.log4j.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * The implementation of Service.
 *
 * @author Yohann.
 */
public class Service_bak {
    private static final Logger logger = Logger.getLogger(Service_bak.class);

    public static AtomicBoolean shutdown = new AtomicBoolean(false);

    // 任务队列
    final private BlockingQueue<MessageHolder> taskQueue = TaskQueue.getQueue();

    private final int THREAD_COUNT = 3;//Runtime.getRuntime().availableProcessors();

    // 执行业务的线程池
    final private ExecutorService taskExecutor = new ThreadPoolBuilder.FixedThreadPoolBuilder().
            setThreadNamePrefix("deal_thread").setPoolSize(THREAD_COUNT).build();

    public Service_bak()  {


    }

    public void initAndStart() {
        start();
        logger.info("初始化服务完成，THREAD_COUNT="+THREAD_COUNT);
    }

    private void start() {
        for(int i=0;i<THREAD_COUNT;i++){
            taskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    while (!shutdown.get()) {
                        try {
                            MessageHolder messageHolder = taskQueue.take();
                            logger.info("TaskQueue取出任务: taskQueue=" + taskQueue.size());
                            logger.info("开始执行取出的任务 messageHolder=" + messageHolder);
                            Dispatcher.dispatch(messageHolder);
                            logger.info("任务处理结束");
                        } catch (InterruptedException e) {
                            logger.warn("receiveQueue take", e);
                        }
                    }
                }
            });
        }

        logger.info("启动服务完成");
    }
}
